這篇終於要開始學習指令,先從v-bind開始介紹,單純用JavaScript來控制的屬性,需要寫蠻多的程式碼,只要使用Vue的指令會省略很多,以下開始實作吧!
1.綁定Style定義data內style的資料,用資料來控制畫面樣式:
const vm = Vue.createApp({
  data() {
    return {
      text: 'Hello Vue!!',
      style: {
        color: "#0095C0",
        background: "#000",
      }
    }
  }
}).mount('#app');
<div id="app">
  <div :style="style">{{ text }}</div>
</div>
以上用物件格式寫到style裡面,如果用陣列格式可以改成以下:
const vm = Vue.createApp({
  data() {
    return {
      text: 'Hello Vue!!',
      red: {
        color:"#0095C0",
      },
      blackbBg: {
        background: "#000",
      }
    }
  }
}).mount('#app');
<div id="app">
  <div :style="[red,blackbBg]">{{ text }}</div>
</div>
2.綁定Class需要動態綁動Class時,可以 { } 大括號撰寫判斷式,而動態的關鍵,就是data裡isAcrive的值:
const vm = Vue.createApp({
  data() {
    return {
      text: 'Hello Vue!!',
      isAcrive: true,
    }
  }
}).mount('#app');
data建立一個isAcrive變數,來決定是否要套用ClassName。
<div id="app">
  <div class="bgblue" :class="{active: isAcrive}">{{ text }}</div>
</div>
v-bild:class="{'要綁定的className': 判斷式}"},data的isAcrive如果是true就套用,如果是false就不套用。
使用三元運算子做更多變化:
const vm = Vue.createApp({
  data() {
    return {
      text: 'Hello Vue!!',
      isAcrive: true,
    }
  }
}).mount('#app');
沿用上一個JavaScript。
<div id="app">
  <div class="active"
  :class="[ isAcrive? 'bgblue' : 'bgred' ]" 
  @click="isAcrive = !isAcrive">{{ text }}
  </div>
</div>
v-bind:class="[判斷式? '結果為true的 Class': '結果為false的 Class']",利用點擊事件達到控制data裡的isAcrive值,從而改變className。
v-biud除了可以綁定style、class,還有很多標籤屬性可以做綁定,像是常見的id,圖片的src,連結的href等DOM都可以透過v-biud來達到動態的效果,以上有用到 :都是v-biud的縮寫,是v-bind綁定後的屬性。
Vue.js 的黑魔法:指令
Vue官網
Vue筆記
v-bind動態綁定
![]()